require([
    "dojo/store/Memory", "dijit/tree/ObjectStoreModel", "dijit/Tree",
    'dojo/request', 'dojo/dom', "dojo/_base/array",
    'dojo/_base/lang', 'dojox/grid/DataGrid', 'dojo/data/ItemFileWriteStore',
    "dojo/domReady!"
], function (Memory, ObjectStoreModel, Tree, request, dom, array, lang, DataGrid, ItemFileWriteStore) {
    var navUrl = dom.byId("nav-url").value;
    var data = [
        {"id": "all", "name": "All", "type": "all"},
        {
            "id": "daily",
            "name": "Daily Review",
            "parent": "all",
            "type": "daily"
        },
        {"id": "weekly", "name": "Weekly Review", "parent": "all", "type": "weekly"},
        {
            "id": "monthly",
            "name": "Monthly Review",
            "parent": "all",
            "type": "monthly"
        }];
    var myStore = new Memory({
        data: data,
        getChildren: function (object) {
            return this.query({parent: object.id});
        }
    });

    var myModel = new ObjectStoreModel({
        store: myStore,
        query: {id: 'all'}
    });

    var tree = new Tree({
        model: myModel,
        showRoot: false,
        onClick: function (item, node) {
            console.log(item);
        }
    }, 'categories-tree');
    tree.startup();
    request(navUrl, {
        handleAs: 'json',
        query: {
            name: 'tom'
        }
    }).then(function (result) {
        array.forEach(result, function (item) {
            data.push(item);
        });
    });
});

require(['dojo/parser', 'dijit/registry', 'dijit/form/Button', 'dojo/date'], function (parser, registry, Button, date) {
    parser.parse();

    var addNode = new Button({
        onClick: function () {
            var tree = registry.byId("categories-tree"),
                dialog = null;
            if (tree.selectedItem && tree.selectedItem.type == 'daily') {
                dialog = registry.byId("daily-dialog");
                dialog.setAttribute('title', 'Add ' + tree.selectedItem.name);
            } else {
                dialog = registry.byId('range-dialog');
                dialog.setAttribute('title', 'Add ' + (tree.selectedItem || {'name': ' Node'}).name);
                var startDate = registry.byId("start-date"),
                    now = new Date();
                switch (tree.selectedItem.type) {
                    case 'weekly':
                        startDate.setValue(date.add(now, "day", -6));
                        break;
                    case 'monthly':
                        startDate.setValue(date.add(now, "day", -1 * date.getDaysInMonth(now)));
                        break;
                    default:
                        break;
                }
            }
            dialog.show();
        }
    }, 'add-node').startup();
});